<?php
class LZ_Category
{
	var $table = 'category';
	
	var $id = 'category_id';
	var $name = 'name';
	var $description = 'description';
	var $order_id = 'order_id';	
	
	function LZ_Category()
	{
		$this->table = LZ_MYSQL_PREFIX.$this->table;
		$this->option_table = LZ_MYSQL_PREFIX.$this->option_table;
	}

	function add( $data = array())
	{
		global $db;
		$sql = make_insert_sql($this->table,$data);
		if ($db->query($sql))
		{
			lz_update();
			if ($data['url_name'])
			{
				$cid = $db->insert_id();
				lz_make_category($data['url_name'],array('page_type'=>'category','cid'=>$cid));
			}
			return true;
		}
		else return false;
	}
	
	function update($id, $data = array())
	{
		global $db;
		if ($data['url_name'])
		{
			if (file_exists(LZ_TOPPATH.$data['url_name']))
				return lang('ALREADY_EXISTS');
			else
				$old = $this->get_one($id);
		}
		
		$sql = make_update_sql($this->table,$data, array('category_id' => $id)); 
		if ($db->query($sql))
		{
			if ($data['url_name'] && $data['url_name'] != $old['url_name'])
			{
				if ($old['url_name'] && is_dir(LZ_TOPPATH.$old['url_name'])) lz_mv($old['url_name'],$data['url_name']);
			}
			$this->update_html($id);
			return true;
		}
	}
	
	function update_html($id)
	{
		lz_update();
		$category = $this->get_one($id);
		lz_update($category['url_name'].'/');
	}
	
	function delete($id)
	{
		global $db;
		$category = $this->get_one($id);
		$sql = "DELETE FROM `$this->table` WHERE `$this->id` = '$id'";
		if ($db->query($sql))
		{
			lz_update();
			return lz_delete($category['url_name']);
		}
		else
			return false;
	}
	
	function get_one($id)
	{
		global $db;
		$sql = "SELECT * FROM `{$this->table}` WHERE `{$this->id}` = '$id' LIMIT 1";
		return $db->get_one($sql);
	}

	/*
	*Input: array
	*  search: like %{search}%
	*  order: order by {order}
	*  desc? 'DESC': 'ASC'
	*  from total: LIMIT {from},{total}
	*  total: LIMIT {total}
	*/
	function get_list($data=array())
	{
		global $db;
		$sql = "SELECT * FROM `{$this->table}` WHERE 1=1 ";
		if ($data['search'])
		{
			$sql.=" AND (`$this->name` LIKE '%".$data['search']."%' OR `$this->description` LIKE '%".$data['search']."%' )";
		}
		if (isset($data['parent_id'])) $sql.=" AND $this->parent_id='".$data['parent_id']."' ";
		$sql.= " ORDER BY ";
		
		if ($data['order'])
		{
			$sql.= $data['order'];
			$sql.= ($data['desc'])?' DESC':' ASC';
		}
		else
		{
			$sql.= $this->order_id.' DESC';
		}

		

		if ($data['from'] && $data['total'])
		{
			$sql.=" LIMIT ".$data['from'].",".$data['total'];
		}
		else if ($data['total'])
		{
			$sql.=" LIMIT ".$data['total'];
		}
		$sql.= ';';
		return $db->get_all($sql);
	}
}
?>